#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstdlib>
#include <strings.h>
#include <unistd.h>   
#include <string.h>
// tcp_client server_ip server_port
void Usage(std::string proc)
{
    std::cout << "Usage\n\t" << proc << "server_ip " << "server_port" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    std::string srv_ip = argv[1];
    uint16_t srv_port = static_cast<uint16_t>(atoi(argv[2]));
    // 创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        std::cerr << "socket error" << std::endl;
        return 2;
    }

    // 2.client不需要显示的绑定， 也不需要listen和accept
    // client需要connect服务器
    struct sockaddr_in server;
    // The bzero() function sets the first n bytes of the area starting at s to zero (bytes containing '\0')
    bzero(&server, sizeof(server));//一般用memset
    server.sin_family = AF_INET;
    // 函数作用有两个，将点分十进制转换为4字节IP，将4字节的主机序列转换为网络序列
    server.sin_addr.s_addr = inet_addr(srv_ip.c_str());
    // 16位主机序列转换为网络序列
    server.sin_port = htons(srv_port);
    if(connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0)
    {
        std::cerr << "connect error" << std::endl;
        return 3;
    }

    std::cout << "connect success!" << std::endl;
    // 3, 进行业务请求了
    while(true)
    {
        std::string buffer;
        std::cout << "please Enter#";
        getline(std::cin, buffer);
        write(sock, buffer.c_str(), buffer.size());

        char ret[1024];
        bzero(ret, sizeof(ret));
        ssize_t cnt = read(sock, ret, sizeof(ret));
        if(cnt > 0)
        {
            ret[cnt] = 0;
            std::cout << "server# " << ret << std::endl;
        }
    }
    return 0;
}